<template>
  <div class="flight-search-page">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>机票查询</span>
          <el-button 
            type="text" 
            @click="toggleSearch"
            :icon="isSearchCollapsed ? 'ArrowDown' : 'ArrowUp'"
          >
            {{ isSearchCollapsed ? '展开' : '收起' }}
          </el-button>
        </div>
      </template>
      
      <el-collapse-transition>
        <div v-show="!isSearchCollapsed">
          <el-form 
            :model="searchForm" 
            :inline="true" 
            class="search-form"
            label-width="120px"
          >
            <!-- 基本信息 -->
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="出发地">
                  <el-select 
                    v-model="searchForm.dept" 
                    placeholder="请选择出发地"
                    filterable
                    clearable
                    style="width: 100%"
                  >
                    <el-option 
                      v-for="departure in flightStore.getDeparturesList" 
                      :key="departure.dept" 
                      :label="departure.dept" 
                      :value="departure.dept" 
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="目的地">
                  <el-select 
                    v-model="searchForm.arr" 
                    placeholder="请选择目的地"
                    filterable
                    clearable
                    style="width: 100%"
                  >
                    <el-option 
                      v-for="destination in flightStore.getDestinationsList" 
                      :key="destination.arr" 
                      :label="destination.arr" 
                      :value="destination.arr" 
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="航班号">
                  <el-input 
                    v-model="searchForm.fno" 
                    placeholder="请输入航班号"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="航司">
                  <el-select 
                    v-model="searchForm.carrier" 
                    placeholder="请选择航司"
                    filterable
                    clearable
                    style="width: 100%"
                  >
                    <el-option 
                      v-for="carrier in flightStore.getCarriersList" 
                      :key="carrier.carrier" 
                      :label="carrier.carrier" 
                      :value="carrier.carrier" 
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 日期范围 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="出发日期范围">
                  <el-date-picker
                    v-model="departureDateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 价格范围
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="价格范围">
                  <el-input-number 
                    v-model="searchForm.min_price" 
                    placeholder="最低价格"
                    :min="0"
                    :precision="2"
                    style="width: 45%"
                  />
                  <span style="margin: 0 10px">-</span>
                  <el-input-number 
                    v-model="searchForm.max_price" 
                    placeholder="最高价格"
                    :min="0"
                    :precision="2"
                    style="width: 45%"
                  />
                </el-form-item>
              </el-col>
            </el-row> -->
            
            <!-- 操作按钮 -->
            <el-row>
              <el-col :span="24" style="text-align: center">
                <el-button type="primary" @click="handleSearch" :loading="flightStore.isLoading">
                  <el-icon><Search /></el-icon>
                  查询
                </el-button>
                <el-button @click="handleReset">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-transition>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>查询结果</span>
          <span class="total-info" v-if="flightStore.total > 0">
            共 {{ flightStore.total }} 条记录
          </span>
        </div>
      </template>

      <el-table 
        :data="flightStore.flightData" 
        v-loading="flightStore.isLoading"
        stripe
        style="width: 100%"
        height="600"
        :key="tableKey"
        :expand-row-keys="expandedRowKeys"
        @expand-change="handleExpandChange"
        row-key="id"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <!-- 价格趋势详情内容 -->
            <div class="expand-content">
              <div class="expand-header">
                <h4>价格趋势图 - 航班号: {{ row.fno }}</h4>
                <p>路线: {{ row.dept }} → {{ row.arr }}</p>
                <p>出发时间: {{ formatDateTime(row.depttime) }}</p>
              </div>
              <div class="chart-container">
                <div 
                  v-if="flightStore.getChartDataById(row.id).value" 
                  :id="`chart-${row.id}`" 
                  class="price-chart"
                ></div>
                <div v-else class="chart-loading">
                  <el-skeleton :rows="3" animated />
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="id" label="ID" min-width="80" width="100" />
        <el-table-column prop="fno" label="航班号" min-width="120" />
        <el-table-column prop="dept" label="出发地" min-width="100" />
        <el-table-column prop="arr" label="目的地" min-width="100" />
        <el-table-column prop="depttime" label="出发时间" min-width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.depttime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleToggleDetail(row.id)"
              :loading="flightStore.getIsLoadingPriceTrend(row.id).value"
            >
              <el-icon><View /></el-icon>
              {{ flightStore.isRowExpanded(row.id).value ? '收起' : '详情' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="flightStore.total > 0">
        <el-pagination
          :current-page="flightStore.currentPage"
          :page-size="flightStore.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="flightStore.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import { Search, Refresh, View } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { useFlightStore } from './stores/flightStore'

const flightStore = useFlightStore()

// 响应式数据
const isSearchCollapsed = ref(false)
const departureDateRange = ref<[string, string] | null>(null)
const tableKey = ref(0) // 用于强制表格重新渲染
const expandedRowKeys = ref<string[]>([])

// 搜索表单
const searchForm = reactive({
  current_page: 1,
  page_size: 20,
  dept: undefined,
  arr: undefined,
  depttime_start: undefined,
  depttime_end: undefined,
  fno: undefined,
  carrier: undefined,
  min_price: undefined as number | undefined,
  max_price: undefined as number | undefined
})

// 方法
function toggleSearch() {
  isSearchCollapsed.value = !isSearchCollapsed.value
}

async function handleSearch() {
  // 处理日期范围
  if (departureDateRange.value) {
    searchForm.depttime_start = departureDateRange.value[0]
    searchForm.depttime_end = departureDateRange.value[1]
  } else {
    searchForm.depttime_start = undefined
    searchForm.depttime_end = undefined
  }

  // 更新搜索条件并查询
  flightStore.updateSearchCondition(searchForm)
}

function handleReset() {
  // 重置表单
  Object.keys(searchForm).forEach(key => {
    if (key === 'current_page') {
      (searchForm as any)[key] = 1
    } else if (key === 'page_size') {
      (searchForm as any)[key] = 20
    } else {
      (searchForm as any)[key] = undefined
    }
  })
  
  departureDateRange.value = null
  
  // 重置store
  flightStore.resetSearchCondition()
}

async function handleSizeChange(size: number) {
  flightStore.handleSizeChange(size)
}

async function handleCurrentChange(page: number) {
  flightStore.handlePageChange(page)
}

// 切换详情展开状态
function handleToggleDetail(id: string) {
  flightStore.toggleRowExpansion(id)
  // 不再强制重新渲染整个表格，只更新需要的部分
  updateExpandedRowKeys()
}

// 更新展开行keys
function updateExpandedRowKeys() {
  expandedRowKeys.value = Array.from(flightStore.expandedRows)
}

// 监听展开状态变化，更新展开行keys
watch(
  () => flightStore.expandedRows,
  () => {
    updateExpandedRowKeys()
    // 等待DOM更新后渲染图表
    nextTick(() => {
      renderCharts()
    })
  },
  { deep: true }
)

// 监听图表数据变化，重新渲染图表
watch(
  () => flightStore.chartData,
  () => {
    nextTick(() => {
      renderCharts()
    })
  },
  { deep: true }
)

// 确保图表容器存在后再渲染
function ensureChartContainerAndRender(id: string, chartData: { dates: string[], prices: number[], decrease_flags: number[] }) {
  let retryCount = 0
  const maxRetries = 10
  
  const checkAndRender = () => {
    const chartDom = document.getElementById(`chart-${id}`)
    if (chartDom && chartDom.offsetParent !== null) { // 检查元素是否可见
      console.log(`渲染图表，ID: ${id}`, chartData)
      renderChart(id, chartData)
    } else if (retryCount < maxRetries) {
      retryCount++
      console.log(`图表容器未准备好，ID: ${id}，重试 ${retryCount}/${maxRetries}`)
      setTimeout(checkAndRender, 100)
    } else {
      console.error(`图表ID: ${id} 渲染失败，已重试 ${maxRetries} 次`)
    }
  }
  
  checkAndRender()
}

// 渲染所有图表
function renderCharts() {
  nextTick(() => {
    flightStore.flightData.forEach(row => {
      if (flightStore.isRowExpanded(row.id).value && row.id) {
        const chartData = flightStore.getChartDataById(row.id).value
        if (chartData && chartData.dates.length > 0) {
          ensureChartContainerAndRender(row.id!, chartData)
        }
      }
    })
  })
}

// 渲染单个图表
function renderChart(id: string, chartData: { dates: string[], prices: number[], decrease_flags: number[] }) {
  const chartDom = document.getElementById(`chart-${id}`)
  if (!chartDom || !id) {
    console.error(`找不到图表容器，ID: ${id}`)
    return
  }
  
  console.log(`初始化图表，ID: ${id}`, chartData)
  const chart = echarts.init(chartDom)
  
  // 准备标记点数据
  const markPoints = []
  for (let i = 0; i < chartData.decrease_flags.length; i++) {
    if (chartData.decrease_flags[i] === 1) {
      markPoints.push({
        coord: [chartData.dates[i], chartData.prices[i]],
        symbol: 'arrow',
        symbolSize: 15,
        symbolRotate: -180,
        itemStyle: {
          color: '#ff0000'
        }
      })
    }
  }
  
  // 计算Y轴的最小值、最大值和间隔
  const prices = chartData.prices;
  const minY = Math.floor(Math.min(...prices) / 100) * 100; // 向下取整到百位
  const maxY = Math.ceil(Math.max(...prices) / 100) * 100;  // 向上取整到百位
  const intervalY = Math.ceil((maxY - minY) / 5 / 100) * 100; // 计算合适的间隔，使Y轴显示5-6个刻度
  
  // 使用所有数据点，但调整X轴标签的显示间隔
  const xAxisData = chartData.dates;
  const pricesData = chartData.prices;
  
  // 根据数据量来自适应X轴标签间隔，确保标签不会过于密集
  let xAxisLabelInterval = 0; // 默认显示所有标签
  if (xAxisData.length > 48) {
    xAxisLabelInterval = 7; // 数据量大于48时，每8个点显示一个标签
  } else if (xAxisData.length > 36) {
    xAxisLabelInterval = 5; // 数据量大于36时，每6个点显示一个标签
  } else if (xAxisData.length > 24) {
    xAxisLabelInterval = 3; // 数据量大于24时，每4个点显示一个标签
  } else if (xAxisData.length > 12) {
    xAxisLabelInterval = 2; // 数据量大于12时，每3个点显示一个标签
  } else if (xAxisData.length > 6) {
    xAxisLabelInterval = 1; // 数据量大于6时，每2个点显示一个标签
  }

  const option = {
    title: {
      text: '价格趋势',
      textStyle: {
        fontSize: 14,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params: any) {
        const param = params[0]
        return `${param.axisValue}<br/>价格: ¥${param.value.toFixed(2)}`
      }
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLabel: {
        rotate: 45,
        fontSize: 12,
        interval: xAxisLabelInterval,
        formatter: function(value: string) {
          // 格式化时间显示，确保清晰可读
          return value.replace(/\//g, '-');
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '价格 (¥)',
      min: minY,
      max: maxY,
      interval: intervalY,
      axisLabel: {
        formatter: '¥{value}',
        fontSize: 12
      }
    },
    series: [{
      name: '价格',
      type: 'line',
      data: pricesData,
      smooth: true,
      lineStyle: {
        color: '#409EFF',
        width: 2
      },
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(64, 158, 255, 0.3)'
          }, {
            offset: 1, color: 'rgba(64, 158, 255, 0.1)'
          }]
        }
      },
      markPoint: {
        data: markPoints,
        label: {
          show: false
        }
      }
    }],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    }
  }
  
  chart.setOption(option)
  
  // 响应式
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 格式化日期时间
function formatDateTime(dateTime: string | Date | undefined): string {
  if (!dateTime) return '-'
  try {
    const date = new Date(dateTime)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return String(dateTime)
  }
}

// 监听展开变化
function handleExpandChange(row: any, expandedRows: any[]) {
  const isExpanded = expandedRows.some(expandedRow => expandedRow.id === row.id)
  if (isExpanded !== flightStore.isRowExpanded(row.id).value) {
    handleToggleDetail(row.id)
  }
}

// 生命周期
onMounted(async () => {
  // 初始化选项数据
  await flightStore.initializeOptions()
  
  // 初始查询（如果需要的话）
  // flightStore.fetchFlights()
})
</script>

<style scoped>
.flight-search-page {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-info {
  color: #909399;
  font-size: 14px;
}

.search-form {
  padding: 20px 0;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.el-divider {
  margin: 20px 0;
}

/* 展开行样式 */
.expand-content {
  padding: 20px;
  background-color: #f8f9fa;
}

.expand-header {
  margin-bottom: 20px;
}

.expand-header h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
}

.expand-header p {
  margin: 4px 0;
  color: #606266;
  font-size: 14px;
}

.chart-container {
  background: white;
  border-radius: 6px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.price-chart {
  width: 100%;
  height: 300px;
}

.chart-loading {
  width: 100%;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
